package com.helloscala.model

import org.bson.types.ObjectId
import org.joda.time.DateTime
import org.squeryl.KeyedEntity

import net.liftweb.common.Box

import yangbajing.util.Pagination
import yangbajing.util.Imports.Y

import MyTypeMode._

object MMicroChatReply {
  def insert(microChatId: String, creator: String, replyText: String): Box[MMicroChatReply] =
    Y.tryBox {
      val mcr = MMicroChatReply(microChatId, creator, replyText)
      transaction(Entities.microChatReplys insert mcr)
    }

  def pagination(_curPage: Int, _limit: Int, microChatId: Option[String] = None): Pagination[MMicroChatReply] =
    new Pagination[MMicroChatReply] {
      val limit = _limit
      val curPage = _curPage
      val total: Long =
        transaction(from(Entities.microChatReplys)(mcr =>
          _where(mcr) compute count(mcr.id)))

      val page: List[MMicroChatReply] =
        transaction(from(Entities.microChatReplys)(mcr =>
          _where(mcr) select mcr orderBy mcr.created_at.desc).page(offset, limit).toList)

      private def _where(mcr: MMicroChatReply) =
        where(
          mcr.micro_chat_id === microChatId.?
        )
    }

  def size(microChatId: Option[String] = None): Long =
    transaction(from(Entities.microChatReplys)(mcr =>
      where(
        _where(mcr, microChatId)
      ) compute count(mcr.id)))

  def findAll(offset: Int, limit: Int,
              microChatId: Option[String] = None): List[MMicroChatReply] =
    transaction(from(Entities.microChatReplys)(mcr =>
      where(
        _where(mcr, microChatId)
      ) select mcr orderBy mcr.created_at.desc).page(offset, limit).toList)

  @inline
  private def _where(mcr: MMicroChatReply, microChatId: Option[String] = None) =
    mcr.micro_chat_id === microChatId.?
}

case class MMicroChatReply(
                            micro_chat_id: String,
                            creator: String,
                            content: String,
                            created_at: DateTime = DateTime.now(),
                            id: String = ObjectId.get.toString) extends KeyedEntity[String] with MessageTrait

